package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.zbkj.dal.base.enums.BizTypeEnum;
import com.zbkj.dal.common.exception.CrmebException;
import com.zbkj.dal.entity.ba.BizImg;
import com.zbkj.dal.entity.ba.Displace;
import com.zbkj.dal.pojo.request.PageParamRequest;
import com.zbkj.dal.pojo.request.ba.ConcludeDisplaceRequest;
import com.zbkj.dal.pojo.request.ba.CreateDisplaceRequest;
import com.zbkj.dal.pojo.request.ba.QueryDisplaceRequest;
import com.zbkj.dal.pojo.response.ba.DisplaceDetailResponse;
import com.zbkj.dal.pojo.response.ba.DisplaceResponse;
import com.zbkj.dal.common.utils.SecurityUtil;
import com.zbkj.dal.dao.DisplaceMapper;
import com.zbkj.service.service.*;
import com.zbkj.service.util.UserUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 奢品置换 服务实现类
 * </p>
 *
 * @author jhui
 * @since 2023-10-03
 */
@Service
public class DisplaceServiceImpl extends ServiceImpl<DisplaceMapper, Displace> implements DisplaceService {
    @Autowired
    private UserService userService;
    @Autowired
    private SystemAdminService systemAdminService;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private BizImgService bizImgService;
    @Autowired
    private SystemAttachmentService systemAttachmentService;
    @Resource
    private AliSmsServiceImpl aliSmsService;

    @Override
    public List<DisplaceResponse> listMyDisplace(Integer status, PageParamRequest pageParamRequest) {
        List<DisplaceResponse> displaceResponses = Lists.newArrayList();
        Integer userId = userService.getUserIdException();
        LambdaQueryWrapper<Displace> queryWrapper = Wrappers.lambdaQuery(Displace.class);
        queryWrapper.eq(Displace::getUid, userId);
        if (status != null && status != -1) {
            queryWrapper.eq(Displace::getStatus, status);
        }
        queryWrapper.orderByDesc(Displace::getId);
        queryWrapper.last("LIMIT " + (pageParamRequest.getPage() -1) * pageParamRequest.getLimit() + "," + pageParamRequest.getLimit());
        List<Displace> list = list(queryWrapper);

        if (CollectionUtils.isEmpty(list)) {
            return displaceResponses;
        }
        List<BizImg> bizImgs = Lists.newArrayList();
        List<Integer> ids = list.stream().map(m -> m.getId()).distinct().collect(Collectors.toList());
        if (CollUtil.isNotEmpty(ids)) {
            bizImgs = bizImgService.listByBizIds(BizTypeEnum.DISPLACE.getType(), ids);
        }
        for (Displace displace : list) {
            DisplaceResponse displaceResponse = new DisplaceResponse();
            BeanUtils.copyProperties(displace, displaceResponse);
            List<String> paths = bizImgs.stream().filter(p -> ObjectUtils.nullSafeEquals(p.getBizId(), displace.getId())
                            && StringUtils.isNotBlank(p.getPath())).map(m -> m.getPath())
                    .collect(Collectors.toList());
            displaceResponse.setPics(paths);
            displaceResponses.add(displaceResponse);
        }

        return displaceResponses;
    }

    @Override
    public Boolean deleteMyDisplace(Integer id) {
        Integer userId = userService.getUserIdException();
        LambdaQueryWrapper<Displace> queryWrapper = Wrappers.lambdaQuery(Displace.class);
        queryWrapper.eq(Displace::getId, id).eq(Displace::getStatus, 0).eq(Displace::getUid, userId);
        return this.remove(queryWrapper);
    }

    @Override
    public Boolean create(CreateDisplaceRequest createDisplaceRequest) {
        Integer userId = userService.getUserIdException();
        Displace displace = new Displace();
        BeanUtils.copyProperties(createDisplaceRequest, displace);
        displace.setUid(userId);
        displace.setStatus(0);
        displace.setCreateTime(LocalDateTime.now());
        displace.setUpdateTime(LocalDateTime.now());

        //            bizImgService.deleteByBizId(BizTypeEnum.DISPLACE.getType(),)

        return Boolean.TRUE.equals(transactionTemplate.execute((e) -> {
//            bizImgService.deleteByBizId(BizTypeEnum.DISPLACE.getType(),)
            save(displace);
            if (CollUtil.isNotEmpty(createDisplaceRequest.getPics())) {
                createDisplaceRequest.getPics().forEach(c -> {
                    c.setBizId(displace.getId());
                    c.setCreateTime(LocalDateTime.now());
                    c.setUpdateTime(LocalDateTime.now());
                    c.setType(BizTypeEnum.DISPLACE.getType());
                    c.setPath(systemAttachmentService.clearPrefix(c.getPath()));
                });

                bizImgService.saveBatch(createDisplaceRequest.getPics());

                //发送短息
                aliSmsService.sendServiceMsg("奢品置换");
            }
            return Boolean.TRUE;
        }));
    }

    @Override
    public DisplaceDetailResponse detail(Integer id) {
        Displace displace = getById(id);
        if (displace == null) {
            throw new CrmebException("该奢品置换记录不存在");
        }
        DisplaceDetailResponse displaceDetailResponse = new DisplaceDetailResponse();
        BeanUtils.copyProperties(displace, displaceDetailResponse);
        List<BizImg> bizImgs = bizImgService.listByBizId(BizTypeEnum.DISPLACE.getType(), id);
        displaceDetailResponse.setPics(bizImgs);
        return displaceDetailResponse;
    }

    @Override
    public PageInfo<DisplaceResponse> queryDisplace(QueryDisplaceRequest queryDisplaceRequest, PageParamRequest pageParamRequest) {
        LambdaQueryWrapper<Displace> queryWrapper = Wrappers.lambdaQuery(Displace.class);
        if (queryDisplaceRequest.getStatus() != null) {
            queryWrapper.eq(Displace::getStatus, queryDisplaceRequest.getStatus());
        }
        if (queryDisplaceRequest.getBeginDate() != null) {
            queryWrapper.ge(Displace::getCreateTime, queryDisplaceRequest.getBeginDate());
        }
        if (queryDisplaceRequest.getEndDate() != null) {
            queryWrapper.lt(Displace::getCreateTime, queryDisplaceRequest.getEndDate().plusDays(1));
        }
        queryWrapper.orderByDesc(Displace::getId);
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<Displace> list = this.list(queryWrapper);
        PageInfo<Displace> pageInfo = PageInfo.of(list);
        PageInfo<DisplaceResponse> result = new PageInfo<>();
        result.setTotal(pageInfo.getTotal());
        List<DisplaceResponse> dtos = Lists.newArrayList();
        for (Displace displace : pageInfo.getList()) {
            DisplaceResponse displaceResponse = new DisplaceResponse();
            BeanUtils.copyProperties(displace, displaceResponse);
            dtos.add(displaceResponse);
        }
        result.setList(dtos);
        UserUtils.fillUsers(result.getList());

        if (CollectionUtils.isNotEmpty(dtos)) {
            List<Integer> adminIds = dtos.stream().filter(p -> p.getOperatorId() != null).distinct().map(m -> m.getOperatorId()).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(adminIds)) {
                Map<Integer, String> nameMapByIdList = systemAdminService.getNameMapByIdList(adminIds);
                for (DisplaceResponse displaceResponse : result.getList()) {
                    if (displaceResponse.getOperatorId() == null) {
                        continue;
                    }
                    displaceResponse.setOperatorName(nameMapByIdList.get(displaceResponse.getOperatorId()));
                }
            }
        }
        return result;
    }

    @Override
    public Boolean confirm(ConcludeDisplaceRequest concludeDisplaceRequest) {
        Integer id = SecurityUtil.getLoginUserVo().getUser().getId();
        concludeDisplaceRequest.setOperatorId(id);
        LambdaUpdateWrapper<Displace> updateWrapper = Wrappers.lambdaUpdate(Displace.class);
        updateWrapper
                .set(Displace::getCurrentCode, concludeDisplaceRequest.getCurrentCode())
                .set(Displace::getTargetCode, concludeDisplaceRequest.getTargetCode())
                .set(Displace::getStatus, concludeDisplaceRequest.getStatus())
                .set(Displace::getRemark, concludeDisplaceRequest.getRemark())
                .set(Displace::getOperatorId, concludeDisplaceRequest.getOperatorId())
                .set(Displace::getUpdateTime, LocalDateTime.now())
                .set(Displace::getServiceFee, concludeDisplaceRequest.getServiceFee())
                .eq(Displace::getId, concludeDisplaceRequest.getId());
        return update(updateWrapper);
    }
}
